package au.com.handsunited.service.impl;

import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

import au.com.handsunited.service.EmailService;

/**
 *
 * @author arunda
 */
public class EmailServiceImpl implements EmailService {

	private final JavaMailSender mailSender;
	private final VelocityEngine velocityEngine;
	private final boolean emailNotificationsEnabled;
	private final String fromAddress;


	private static Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);


	/**
	 *
	 * @param mailSender
	 * @param velocityEngine
	 * @param emailNotificationsEnabled
	 * @param fromAddress
	 */
	public EmailServiceImpl(JavaMailSender mailSender, VelocityEngine velocityEngine, boolean emailNotificationsEnabled, String fromAddress) {
		super();
		this.mailSender = mailSender;
		this.velocityEngine = velocityEngine;
		this.emailNotificationsEnabled = emailNotificationsEnabled;
		this.fromAddress = fromAddress;
	}



	/**
	 * @see au.com.handsunited.service.EmailService#sendEmail(java.lang.String, java.lang.String, java.lang.String, java.util.Map)
	 */
	@Override
	public void sendEmail(final String recipient, final String emailTemplate, final String subject, final Map<String, Object> model) {

		if (emailNotificationsEnabled) {
			MimeMessagePreparator preparator = new MimeMessagePreparator() {

				public void prepare(MimeMessage mimeMessage) throws Exception {

					MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
					message.setTo(recipient);
					message.setFrom(fromAddress);
					message.setSubject(subject);
					String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, emailTemplate, model);
					message.setText(text, true);
				}
			};
			mailSender.send(preparator);
		}
	}


}
